const http = require('http')
const createHandler = require('gitee-webhook-handler')
const fs = require('fs')
const spawn = require('await-spawn')
const log4js = require('log4js'),
  logger = log4js.getLogger()
const url = require('url'),
  querystring = require('querystring')

// 初始化配置
log4js.configure({
  appenders: {
    everything: {
      type: 'file',
      filename: 'log/all-the-logs.log',
      maxLogSize: 1024 * 1024 * 5,
      backups: 3,
      compress: true
    }
  },
  categories: {
    default: {
      appenders: ['everything'],
      level: 'debug'
    }
  }
})
// 执行命令
const run = async (sh, web = null) => {
  const bl = await spawn(sh, [])
  logger.level = 'info'
  logger.info(web || '')
  logger.info(bl.toString())
}
// 命令目录
const createDirectory = () => {
  let path = __dirname + '/sh'
  if(!fs.existsSync(path)){
    fs.mkdirSync(path)
    fs.chmodSync(path,7777)
  }
}

const handler = createHandler({
  path: '/',
  secret: 'SEOCD3DEYR4893MBVC3'
})
// 初始化命令目录
createDirectory()
http.createServer(function (req, res) {
  let _url = url.parse(req.url),
    query = querystring.parse(_url.query)
  handler(req, res, err => {
    if(err === undefined){
      logger.level = 'error'
      logger.info(`no permission visit${query.web ?' '+ query.web + '.com':',please configure it!'}`)
      res.statusCode = 404
      res.end(`no permission visit${query.web ? ' ' + query.web +'.com':',please configure it!'}`)
    }
  })
}).listen(7000)

handler.on('error', err => {
  logger.level = 'error'
  logger.info(`create file ${ err.message}`)
})
// Push钩子
handler.on('Push Hook', event => {
  let web = event.payload.web
  let type = event.payload.type || 'thinkPHP'
  let root_path = event.payload.root_path || '/www/wwwroot'
  let path = __dirname + `/sh/${web}`
  let sh = ''
  if (type === 'thinkPHP') {
    sh = `#!/bin/bash
  WEB_PATH='${root_path}/${web}/'
  echo "Start deployment"
  cd $WEB_PATH
  echo "pulling source code..."
  git fetch --all
  git reset --hard origin/master
  git clean -f
  git pull
  echo "changing permissions..."
  chmod -R 7777 $WEB_PATH'runtime/'
  echo "done."`
  } else {
    sh = `#!/bin/bash
  WEB_PATH='${root_path}/${web}/'
  echo "Start deployment"
  cd $WEB_PATH
  echo "pulling source code..."
  git fetch --all
  git reset --hard origin/master
  git clean -f
  git pull
  echo "pull done."`
  }
  
  if(!fs.existsSync(path)){
    fs.writeFileSync(path,sh)
    fs.chmodSync(path, 0711)
    logger.level = 'info'
    logger.info(`init ${web} command!done!`)
  }else{
    run(path, web)
  }
})
// 问题钩子
handler.on('Issue Hook', event => {
  console.log('Received an issue event for %s action=%s: #%d %s',
    event.payload.repository.name,
    event.payload.action,
    event.payload.issue.number,
    event.payload.issue.title)
})